$(function () {
    var tips = [],//中奖提示
        $prize = $(".prize"),//转盘
        $change = $("#change"),//显示剩余抽奖机会
        $info = $(".info"),//中奖提示信息
        number = {count: 1},//次数
        bool = false,//判断是否在旋转，true表示是，false表示否
        timer;//定时器
        $('#ACid').val('');//初始化ACid
        $('#ResultId').val('');
        $change.html(number.count);//初始化次数
    var ActivityID = location.search.split("?ActivityID=")[1];//?ActivityID=88C6EDB4-EA87-4BE7-94FC-7E725782B3D9
    var type = location.search.split('type=')[1];//判断是否为微信公众号还是APP
    
    console.log('navigator.userAgent',navigator.userAgent);
    function is_weixin(){
        var ua = navigator.userAgent.toLowerCase();
        if(ua.match(/MicroMessenger/i)=="micromessenger") {
            return true;
        } else {
            return false;
        }
    }
    if(is_weixin()){
        console.log('微信浏览器')
    }

    $(document).ready(function(){
        //大转盘背景动效
        init();
        function init() {
            timer = setInterval(function () {
                $(".ring").toggleClass("light");
            }, 1000);
        }
        //用户验证接口
        $.ajax({
            type: "post",
            //url: "https://59.110.222.131/SCRM_API/api/Activity/getActivityUserValidResult",
			url: "",
            contentType: 'application/json',
            data: JSON.stringify({
                "UserSource":"1",//0.微信公众号，1.微信用户，2.APP，3.其他
                "WebChatId":"NKCRM",//公众号ID
                "OpenID":"o94UKwmg0Il_F5R5Vegd0rCffAPw",//用户OpenID，如果是公众号，就是公众号下的OpenID，如果是微信用户，则是微信用户的OpenID，如果是APP用户，则是APP用户的唯一标识。
                "ActivityID":"88C6EDB4-EA87-4BE7-94FC-7E725782B3D9",//活动ID
                "token":"18E58B5C7D4B2A5161865B53641513B7F8B6FE3892C3593EA26495D483B278D4ED68AD9D1670A359A5173E7705FC1F2A487C19612381C8A5E991F1B4829211F7295C417C9A6F99B26ED79838DA9BDB75DC5D937714A45B5A915CAC46B7F30B00"
            }), success: function (data, status) {
                //alert(JSON.stringify(data));
                console.log(JSON.stringify(data));
                if(data.code == '0'){
                    var data = data.data;
                    var LotteryItemInfo = [];
                    var Begin_date = data.Begin_date,//开始时间
                        End_date = data.End_date,//结束时间
                        LotteryList = data.LotteryItemInfo,//奖品列表
                        //RadomResult = data.RadomResult,//中奖信息列表
                        banner = data.ActivityBannerURL,//活动横幅
                        title = data.TitleBannerURL,//title背景
                        ActivityRule = data.ActivityRule,//活动规则
                        name = data.Name;//活动名
                        $('#ACid').val(ACid)//隐藏域

                    $('#Begin_date').html(Begin_date);//开始时间
                    $('#End_date').html(End_date);//结束时间
                    document.title = name;//标题
                    //banner
                    if(banner){
                        $('.banner').css('background-image','url('+banner+')');
                    }else{
                        $('.banner').css('background-image','url("../image/banner.png")');
                    }
                    //title
                    if(title){
                        $('.border').css('background-image','url('+title+')');
                    }else{
                        $('.border').css('background-image','url("../image/banner.png")');
                    }
                    //活动规则
                    if(ActivityRule){
                        $('.ActivityRule').html(ActivityRule)
                    }else{
                        $('.ActivityRule').html('活动规则')
                    }


                    //奖品列表
                    var dom = '',
                        prizeList = '',
                        resultList = '';
                    for(var i=0,list = LotteryList;i<8;i++){
                        if(list[i]){
                            dom +=  '<li><span></span><p>'+list[i].AwordItem.Name+'</p>'+'<img src="'+list[i].DetailImgURL+'"></li>'
                        }else{
                            dom +=  '<li><span></span><p>谢谢参与</p><img src="./image/face.png"></li>'
                        }
                    }
                    $('#LotteryList').html(dom)
                    //活动奖品列表
                    for(var j=0;j<LotteryList.length;j++){
                        prizeList += '<li>【<span>奖品'+(j+1)+'</span>】'+list[j].AwordItem.Name+'</li>'
                    }
                    $('#prizeList').html(prizeList);
                    RadomResult =  [
                        {
                            nickName: "张一",
                            LotteryItemInfoName: "奖品1",
                        },
                        {
                            nickName: "张一二",
                            LotteryItemInfoName: "奖品2",
                        },
                        {
                            nickName: "张一二三",
                            LotteryItemInfoName: "奖品3",
                        },
                        {
                            nickName: "张一二三四",
                            LotteryItemInfoName: "奖品4",
                        },
                        {
                            nickName: "张一二三四五",
                            LotteryItemInfoName: "奖品5",
                        }
                    ];
                    //中奖信息列表
                    for(var k=0;k<RadomResult.length;k++){
                        var nickName = RadomResult[k].nickName;//获奖者昵称
                        var name = RadomResult[k].LotteryItemInfoName;//奖项名
                        var left = nickName.split('')[0];
                        var right = nickName.split('')[nickName.split('').length-1];
                        resultList += '<li>恭喜<span class="start-num">'+left+'</span>*<span class="end-num">'+right+'</span>获得<span class="info">'+name+'</span>一份</li>'
                    }
                    $('#sItem').append(resultList);
                }
            },
            error:function(data){
                $.DialogByZ.Alert({Title: "提示", Content:'请联系管理员!',BtnL:"确定",FunL:CloseLayer});
            }
        });

        //点击抽奖
        $("#btn").click(function () {
            if (bool) return; // 如果在执行就退出
            bool = true; // 标志为 在执行
            if (number.count <= 0) { //当抽奖次数为0时
                $change.html(0);//次数显示为0
                bool = false;
                $.DialogByZ.Alert({Title: "提示", Content:'没有次数了!',BtnL:"确定",FunL:CloseLayer});
            } else { //还有次数就执行
                number.count--;
                number.count <= 0 && (number.count = 0);
                $change.html(number.count);//显示剩余次数
                $prize.removeClass("running");
                //抽奖接口
                $.ajax({
                    type: "post",
                    //url: "https://59.110.222.131/SCRM_API/api/Activity/ExecuteLottory",
					url: "",
                    contentType: 'application/json',
                    data: JSON.stringify({
                        "UserSource":"1",//0.微信公众号，1.微信用户，2.APP，3.其他
                        "WebChatId":"NKCRM",//公众号ID
                        "OpenID":"o94UKwmg0Il_F5R5Vegd0rCffAPw",//用户OpenID，如果是公众号，就是公众号下的OpenID，如果是微信用户，则是微信用户的OpenID，如果是APP用户，则是APP用户的唯一标识。
                        "ActivityID":ActivityID,//活动ID
                        "token":"18E58B5C7D4B2A5161865B53641513B7F8B6FE3892C3593EA26495D483B278D4ED68AD9D1670A359A5173E7705FC1F2A487C19612381C8A5E991F1B4829211F7295C417C9A6F99B26ED79838DA9BDB75DC5D937714A45B5A915CAC46B7F30B00"
                    }), success: function (data, status) {
                        //alert(JSON.stringify(data));
                        console.log(JSON.stringify(data));
                        if(data.code == '0'){
                            var data = data.data,
                                sNum = '',
                                esNum = '';
                            var name = data.LotteryItemInfo.AwordItem.Name,//奖品名
                                time = data.LotteryItemInfo.AwordItem.AwardExpiredDesc,//有效期
                                nickName = data.nickName,//用户昵称
                                ResultId = data.ResultId;//奖品ID
                            $('#ResultId').val(ResultId);//获奖ID隐藏域
                            rotateFn(0, time);
                            $('.Lottery-name').html(name+'!');//中奖信息弹框
                        }
                    },
                    error:function(data){
                        $.DialogByZ.Alert({Title: "提示", Content:'请联系管理员!',BtnL:"确定",FunL:CloseLayer});
                    }
                });
            }
        });

        //选中函数。参数：奖品序号、角度、提示文字、有效期
        function rotateFn(angle,time) {
            $('.expiryDate').html('有效期：'+time);//有效期
            var Item = '';
            bool = true;
            $prize.stopRotate();
            $prize.rotate({
                angle: 0,//旋转的角度数
                duration: 4000, //旋转时间
                animateTo: angle + 1440, //给定的角度,让它根据得出来的结果加上1440度旋转。也就是至少转4圈
                callback: function () {
                    bool = false; // 标志为 执行完毕
                    win();
                }
            });
        }

        //我的奖品中地址提交
        $('.submit').on('click',function(){
            var ResultId = $('#ResultId').val();
            if(ResultId == ''){
                $.DialogByZ.Alert({Title: "提示", Content:'您还没有奖品!',BtnL:"确定",FunL:CloseLayer});
            }else{
                var Phone = $('.Phone').val(),
                    Receiver = $('.Receiver').val(),
                    Address = $('.Address').val(),
                    Email = $('.Email').val();
                if( Phone == ''){
                    $.DialogByZ.Alert({Title: "提示", Content:'请输入手机号！',BtnL:"确定",FunL:CloseLayer});
                    return
                }else if(Receiver == ''){
                    $.DialogByZ.Alert({Title: "提示", Content:'请输入收件人姓名！',BtnL:"确定",FunL:CloseLayer});
                    return
                }else if(Address == ''){
                    $.DialogByZ.Alert({Title: "提示", Content:'请输入地址！',BtnL:"确定",FunL:CloseLayer});
                    return
                }else if(Email == ''){
                    alert('请输入邮箱地址！');
                    return
                }else{
                    $.ajax({
                        type: "post",
                        //url: "https://59.110.222.131/SCRM_API/api/Activity/UpdateLotteryResultShippingInfo",
						url: "",
                        contentType: 'application/json',
                        data: JSON.stringify({
                            "ResultId":ResultId,//抽奖结果标识
                            "PhoneNO":Phone,//电话号码
                            "Receiver":Receiver,//收件人
                            "Address_Detail":Address,//地址
                            "MAIL":Email//邮箱地址
                        }), success: function (data, status) {
                            //alert(JSON.stringify(data));
                            console.log(JSON.stringify(data));
                            if(data.data == true){
                                alert('提交成功');
                                window.location.reload();
                            }
                        },
                        error:function(data){
                            // alert(JSON.stringify(data));
                            alert('请联系管理员！')
                        }
                    });
                }
            }
        });

        var $maskRule = $("#mask-rule"),//我的奖品遮罩层
            $mask = $("#mask"),//红包遮罩层
            $winning = $(".winning"),//红包
            $card = $("#card"),
            $close = $("#close");
        //link = false;//判断是否在链接跳转中

        //我的奖品遮罩层
        $(".myPrize").click(function () {
            var ResultId = $('#ResultId').val();
            $maskRule.show();
            $winning.addClass("reback");
            setTimeout(function () {
                $("#card1").addClass("pull");
            }, 500);
            if(ResultId == '') {
                $('.my-prize').html('您还没有奖品');
            }else{
                //我的奖品接口
                $.ajax({
                    type: "post",
                    //url: "https://59.110.222.131/SCRM_API/api/Activity/QueryLotteryResultDetail?ResultId="+ResultId,
					url: "",
                    contentType: 'application/json',
                    data:{},
                    success: function (data, status) {
                        //alert(JSON.stringify(data));
                        console.log(JSON.stringify(data));
                        if(data.code == '0'){
                            var data = data.data;
                            var name = data.LotteryItemInfo.AwordItem.Name,//奖品名
                                time = data.LotteryItemInfo.AwordItem.AwardExpiredDesc;//有效期
                            $('.my-prize').html(name);//奖品名
                            $('.expiryDate').html('有效期：'+time);//有效期
                        }
                    },
                    error:function(data){
                        // alert(JSON.stringify(data));
                        alert('请联系管理员！')
                    }
                });
            }
        });

        $("#close-rule").click(function () {
            $maskRule.hide();
            $winning.removeClass("reback");
            $("#card1").removeClass("pull");
        });

        //提交地址遮罩层
        $(".address").click(function () {
            $('#address').show();
        });

        $('.close').click(function () {
            $('#address').hide();
        });

        /*中奖信息提示*/
        function win() {

            //遮罩层显示
            $mask.show();
            $winning.addClass("reback");
            setTimeout(function () {
                $card.addClass("pull");
            }, 500);

            //关闭弹出层
            $("#close,.win,.btn").click(function () {
                //$close.click(function () {
                $mask.hide();
                $winning.removeClass("reback");
                $card.removeClass("pull");
            });
        }

        //关闭弹框
        function CloseLayer() {
            $.DialogByZ.Close();
        }
    });
});
